import os
from flask import Flask, request,Response
import dashscope
import threading
from APIResponse import APIResponse
from sqlite3 import Error
import sqlite3
app = Flask(__name__)

dashscope.api_key = 'sk-fd107094739d4c1b9ce8cbc55902a3a2'
dashscope_lock = threading.Lock()
current_dir = os.path.dirname(__file__)
db_path = os.path.join(current_dir,'..','..','StreamingAssets','test.db')

@app.route("/GetLLMAnswer",methods=['Post'])
def GetLLMAnswer():
    tips = request.json.get("tips")
    backstory = request.json.get("backstory")
    currentInfo = request.json.get("currentInfo")
    with dashscope_lock:
        messages = [{'role': 'user', 'content':'请填写<>内的空间，<>内部的文字是提示。\n' + tips + backstory + currentInfo + '你打算去<地点>，干<行为>，<数字>分钟。\n尽量避免重复同一个行为，但是如果之前的行为因为对话而被打断，那么要根据对话的内容去决定具体的行为\n重点：注意只输出<>中要求你填写的文字或数字，且只输出一组结果，不要过多输出，不要输出<地点>、<行为>、<数字>，不要输出<>，只输出你填写的文字，只输出你填写的文字，不要输出单位\n重点：输出<地点>时注意要在给出的地点中选择\n重点：输出时用,隔开，中间不要加空格'}]
        response = dashscope.Generation.call(model = "deepseek-v3",messages=messages,result_format='message')
    mydict = {'LLMAnswer':response["output"]["choices"][0]["message"]["content"]}
    return APIResponse.make_response(APIResponse.success(mydict))

@app.route("/GetReflection",methods=['Post'])
def GetReflection():
    mydict = {'reflection':''}
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    NPC_Id = request.json.get("NPC_Id")
    methodResponse = GetAddedBackstory(conn,cursor,NPC_Id)
    if not methodResponse['success']:
        return APIResponse.make_response(methodResponse);
    addedBackstory = methodResponse['data']['addedBackstory']
    with dashscope_lock:
        messages = [{'role': 'user', 'content':'以下内容是一个人的行程 ：\n' + addedBackstory + '请你对该内容进行概括，剔除对于之后行为无作用的信息，保留具体的天数信息，重要信息：比如说与别人的约定等信息保留\n只输出概括后的内容'}]
        response = dashscope.Generation.call(model = "deepseek-v3",messages=messages,result_format='message')
        print(messages[0])
        reflection = response["output"]["choices"][0]["message"]["content"]
        mydict["reflection"] = reflection
    try:
        cursor.execute('Update NPCTable SET NPC_LastMemoryDay = NPC_LastMemoryDay + 1, NPC_Memory = ? Where NPC_Id = ?',(reflection,NPC_Id))
        conn.commit()
        cursor.close()
        conn.close()
        return APIResponse.make_response(APIResponse.success(mydict))
    except Error as e:
        cursor.close()
        conn.close()
        return APIResponse.make_response(APIResponse.error(str(e)))

# 遇到另一个NPC，并率先发现，判断是否交谈
@app.route("/TalkorNot",methods=['Post'])
def TalkorNot():
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    myId = request.json.get("myId")
    othersId = request.json.get("othersId")
    othersWords = request.json.get("othersWords")
    myCurrentAction = request.json.get("myCurrentAction")
    othersCurrentAction = request.json.get("othersCurrentAction")
    myDict = {'talkOrNot':False,'talkContent': "",}
    # 获得两NPC之间的关系
    methodResponse = GetRelationship(conn,cursor,myId,othersId)
    if not methodResponse['success']:
        return APIResponse.make_response(methodResponse)
    relationship = methodResponse['data']['relationship']
    # 获得自身的所有信息
    methodResponse = GetBackstory(conn,cursor,myId)
    if not methodResponse["success"]:
        return APIResponse.make_response(methodResponse)
    NPC1_B = methodResponse['data']['backstory']
    # 初始化对方信息
    NPC2_B = ""
    messages = []
    message = ""
    NPC1_B = "你是" + NPC1_B + "你现在正在" + myCurrentAction + "\n"
    if othersWords == "":
        #如果此时为我率先判断是否与另一个NPC对话
        # 根据关系判断如何询问大语言模型
        if relationship == "陌生人":
            NPC2_B = "他正在" + othersCurrentAction
            message = {'role': 'user', 'content': NPC1_B + "你遇到了一个人(你并不认识他)," + NPC2_B + ",你要跟他说话吗?(请以此人的视角来回答)\n要跟他说话回答True否则回答False(只回答True或False)"}
            messages.append(message)
        else:
            methodResponse = GetNPCName(conn,cursor,othersId)
            if not methodResponse["success"]:
                return APIResponse.make_response(methodResponse)
            NPC2_Name = methodResponse["data"]['name']
            NPC2_B = NPC2_Name + ",他正在" + othersCurrentAction
            message = {'role': 'user', 'content': NPC1_B + "你遇到了" + NPC2_B + "\n你跟他有交集,你要跟他说话吗?(请以此人的视角来回答)\n要跟他说话回答True否则回答False(只回答True或False)"}
            messages.append(message)
    else:
        #如果此时我是被对话的一方
        if relationship == "陌生人":
            message = {'role': 'user', 'content': NPC1_B + "有人对你说:" + othersWords + "\n你是否要进行对话？(请以此人的视角来回答)\n进行对话回答True；否则回答False(只回答True或False)"}
        else:
            methodResponse = GetNPCName(conn,cursor,othersId)
            if not methodResponse["success"]:
                return APIResponse.make_response(methodResponse)
            NPC2_Name = methodResponse["data"]['name']
            message = {'role': 'user', 'content': NPC1_B + "有人对你说:" + othersWords + "\n" + "你发现说话的人是" + NPC2_Name + ",你认识他\n你是否要进行对话？(请以此人的视角来回答)\n进行对话回答True；否则回答False(只回答True或False)"}
        messages.append(message)
    print(message)
    response = dashscope.Generation.call(model = "deepseek-v3",messages=messages,result_format='message')
    myDict["talkOrNot"] = bool(response["output"]["choices"][0]["message"]["content"]) # 这是 是否与对方说话 的结果
    message = {"role": "assistant", "content":str(myDict["talkOrNot"])}
    messages.append(message)
    cursor.close()
    conn.close()
    if othersWords == "":
        #如果自己是率先说话的
        if myDict["talkOrNot"]:
            # 如果决定说话
            message = {"role":"user","content": "你打算说什么？(请以此人的视角来回答;注意如果你不认识他，那你要自我介绍一下，但是如果你认识他，你也不要自我介绍了)只回答说话内容"}
            messages.append(message)
    else:
        #如果自己是被说话的,那不管怎么样，都会有回话
        message = {"role":"user","content": "你打算说什么？(请以此人的视角来回答;如果不对话，就说句话表示拒绝)只回答说话内容"}
        messages.append(message)
    response = dashscope.Generation.call(model = "deepseek-v3",messages=messages,result_format='message')
    myDict["talkContent"] = response["output"]["choices"][0]["message"]["content"]
    print(myDict)
        # Python后端获取不到游戏内时间，因此不能在此处直接将对话放到数据库 
        # 也是因为在这里结束不了当前NPC正在干的事情
    return APIResponse.make_response(APIResponse.success(myDict))

# 对话开始，对数据库进行操作
@app.route("/TalkStart",methods=['Post'])
def TalkStart():
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    NPC_Id = request.json.get("NPC_Id")
    EventStartTime = request.json.get("EventStartTime")
    EventStartDay = request.json.get("EventStartDay")
    currentLocation = request.json.get("currentLocation")
    # 对话开启有两种可能，一种是我主动开启，这时候我说的话不为空，但是别人的话为空
    # 另一种是别人主动向我搭话，这时候别人的话不为空，我的话仍然不为空(考虑到礼貌问题，哪怕是拒绝对话，也会向别人说一声)
    # 因此我的话不可能为空，别人的话可能为空
    currentLocation = request.json.get("currentLocation")
    myWords = request.json.get("myWords")
    othersWords = request.json.get("othersWords")
    EventContent = "在" + currentLocation + "发生的对话\n" + (("有人对我说:\"" + othersWords + "\"\n") if othersWords != "" else "") + "我说:\"" + myWords + "\"\n"
    Event = (NPC_Id,EventStartTime,EventStartDay,currentLocation,EventContent)
    methodResponse = EventStart(conn,cursor,Event)
    cursor.close()
    conn.close()
    return APIResponse.make_response(methodResponse)


# 被交谈了，该怎么办,主要是获得自己的回答和反应
@app.route("/Talked",methods=['Post'])
def Talked():
    myId = request.json.get("myId")
    othersId = request.json.get("othersId")
    othersWords = request.json.get("othersWords")
    # 最后结果用result存一下
    myDict = {'continueTalk':False,'talkContent':''}
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()  
    # 不管是什么情况，自身的信息都要给到大语言模型
    methodResponse = GetBackstory(conn,cursor,myId)
    if not methodResponse['success']:
        return APIResponse.make_response(methodResponse)
    myBackstory = "你是" + methodResponse['data']['backstory']
    # 不管正在对话还是没在对话，另一个NPC的名字都是需要的 
    methodResponse = GetNPCName(conn,cursor,othersId)
    if not methodResponse['success']:
        return APIResponse.make_response(methodResponse)
    othersName = methodResponse['data']['name']
    messages = []
    # 如果正在对话中，那说明另一个人已经自我介绍过了，直接将该NPC的姓名给到大语言模型，并让大语言模型判断是否继续该对话
    message = {'role': 'user', 'content': myBackstory + othersName + "说" + othersWords + "\n你是否要继续该对话？(请以此人的视角来回答,注意不要进行过多的无意义对话,注意你们是在原地对话，如果要前往其他位置，那请返回False,进入计划状态)\n继续对话回答True；结束对话回答False(只回答True或False)"}
    print(message)
    messages.append(message)
    response = dashscope.Generation.call(model = "deepseek-v3",messages=messages,result_format='message')
    # 如果正在对话，那获得的就是：是否继续该对话；如果之前没有进行对话，那获得的就是：是否要进行对话
    print(response["output"]["choices"][0]["message"]["content"])
    myDict["continueTalk"] = eval(response["output"]["choices"][0]["message"]["content"]) # 继续(进行)对话吗，继续(进行)为True，不继续(进行)为False
    message = {"role": "assistant", "content":str(myDict["continueTalk"])}
    messages.append(message)
    message = {"role":"user","content": "你打算说什么？(请以此人的视角来回答;如果不再对话，就说句话表示拒绝)只回答说话内容"}
    messages.append(message) 
    # 不管是否要继续 (进行)对话，都要说句话表示表示
    response = dashscope.Generation.call(model = "deepseek-v3",messages=messages,result_format='message')
    myDict["talkContent"] = response["output"]["choices"][0]["message"]["content"]
    print(myDict)
    return APIResponse.make_response(APIResponse.success(myDict))
    # True：表示他要继续(进入)该对话
    # 之后就是该NPC的回答

@app.route("/TalkRecord",methods=['Post'])
def TalkRecord():
    myWords = request.json.get("myWords")
    othersName = request.json.get("othersName")
    othersWords = request.json.get("othersWords")
    talkEventId = request.json.get("talkEventId")
    aSetTalk = (othersName + "说:\"" + othersWords + "\"\n" + "我说:\"" + myWords + "\"\n",talkEventId)
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    methodResponse = TalkRecord(conn,cursor,aSetTalk)
    return APIResponse.make_response(methodResponse)

def TalkRecord(conn,cursor,aSetTalk):
    try:
        cursor.execute('Update EventTable SET EventContent = EventContent || ? WHERE EventId = ?',aSetTalk)
        conn.commit()
        return APIResponse.success(None)
    except Error as e:
        return APIResponse.error(str(e))

# 结束交谈
@app.route("/TalkEnd",methods=['Post'])
def TalkEnd():
    talkEventId = request.json.get("talkEventId")
    myWords = request.json.get("myWords")
    othersName = request.json.get("othersName")
    othersWords = request.json.get("othersWords")
    EventEndTime = request.json.get("talkEndTime")
    aSetTalk =  (othersName + "说:\"" + othersWords + "\"\n" + "我说:\"" + myWords + "\"\n") if myWords != "" else (othersName + "说:\"" + othersWords + "\"\n") + "对话结束"
    talk = (EventEndTime,aSetTalk,talkEventId)
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    methodResponse = TalkEnd(conn,cursor,talk)
    cursor.close()
    conn.close()
    return APIResponse.make_response(methodResponse)
    
def TalkEnd(conn,cursor,talk):
    try:
        cursor.execute('Update EventTable SET EventEndTime = ?,EventContent = EventContent || ? WHERE EventId = ?',talk)
        conn.commit()
        return APIResponse.success(None)
    except Error as e:
        return APIResponse.error(str(e))
    
#NPC关系更新
@app.route("/RelationshipUpdate",methods=['Post'])
def RelationshipUpdate():
    talkEventId = request.json.get("talkEventId")
    NPC_Id1 = request.json.get("NPC_Id1")
    NPC_Id2 = request.json.get("NPC_Id2")
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    methodResponse = RelationshipUpdate(conn,cursor,talkEventId,NPC_Id1,NPC_Id2)
    cursor.close()
    conn.close()
    return APIResponse.make_response(methodResponse)

def RelationshipUpdate(conn,cursor,talkEventId,NPC_Id1,NPC_Id2):
    try:
        cursor.execute('SELECT EventContent FROM EventTable WHERE EventTable.EventId = ?',(talkEventId,))
        conn.commit()
        talkContent = cursor.fetchone()[0]
        if NPC_Id1 > NPC_Id2:
            temp = NPC_Id1
            NPC_Id1 = NPC_Id2
            NPC_Id2 = temp
        elif NPC_Id1 == NPC_Id2:
            return APIResponse.error("两个NPC的ID不能相同")
        cursor.execute('SELECT RelationalDescription FROM RelationshipTable WHERE NPC_Id1 = ? AND NPC_Id2 = ?',(NPC_Id1,NPC_Id2,))
        conn.commit()
        pastRelationship = cursor.fetchone()[0]
        messages = []
        message = {'role': 'user', 'content': talkContent + "\n以上是两个人的对话，他们之前的关系为：" + pastRelationship + "\n请问经过了上述对话，他们的关系变成了什么？(关系分级:陌生人 普通朋友 好友 挚友。请从以上关系中选择其中一个，回答时，只回答最后的关系即可)"}
        messages.append(message)
        response = dashscope.Generation.call(model = "deepseek-v3",messages=messages,result_format='message')
        nowRelationship = response["output"]["choices"][0]["message"]["content"]
        cursor.execute('Update RelationshipTable SET RelationalDescription = ? WHERE NPC_Id1 = ? And NPC_Id2 = ?',(nowRelationship,NPC_Id1,NPC_Id2,))
        conn.commit()
        return APIResponse.success(None)
    except Error as e:
        return APIResponse.error(str(e))




@app.route("/NewNPC",methods=['Post'])
def  NewNPC():
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    NPC_Name = request.json.get("NPC_Name")
    NPC_BaseBackground = request.json.get("NPC_BaseBackground")
    NPC_LastMemoryDay = int(request.json.get("NPC_LastMemoryDay")) 
    NPC_Memory = request.json.get("NPC_Memory")
    NPC = (NPC_Name,NPC_BaseBackground,NPC_LastMemoryDay,NPC_Memory)
    
    methodResponse = NewNPC(conn,cursor,NPC)
    cursor.close()
    conn.close()
    print(methodResponse)
    return APIResponse.make_response(methodResponse)
    
def NewNPC(conn,cursor,NPC):
    myDict = {'NPC_Id':-1}
    try:
        cursor.execute('Insert INTO NPCTable (NPC_Name, NPC_BaseBackground, NPC_LastMemoryDay, NPC_Memory) VALUES  (?, ?, ?, ?)',NPC)
        conn.commit()
        NPC_Id = cursor.lastrowid
        cursor.execute('SELECT NPC_Id FROM NPCTable WHERE NPCTable.NPC_Id != ?',(NPC_Id,))
        conn.commit()
        NPC_Ids = cursor.fetchall()
        for Id in NPC_Ids:
            if NPC_Id < Id[0]:
                cursor.execute('Insert Into RelationshipTable (NPC_Id1, NPC_Id2, RelationalDescription) values (?, ?, ?)',(NPC_Id, Id[0], "陌生人"))
            elif NPC_Id > Id[0]:  
                cursor.execute('Insert Into RelationshipTable (NPC_Id1, NPC_Id2, RelationalDescription) values (?, ?, ?)',(Id[0], NPC_Id, "陌生人"))
            conn.commit()
        myDict["NPC_Id"] = NPC_Id
        return APIResponse.success(myDict)
    except Error as e:
        return APIResponse.error(str(e)) 

@app.route("/EventAdd",methods=['Post'])
def EventAdd():
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    NPC_Id = request.json.get("NPC_Id")
    EventStartTime = request.json.get("EventStartTime")
    EventStartDay = request.json.get("EventStartDay")
    EventEndTime = request.json.get("EventEndTime")
    EventPlace = request.json.get("EventPlace")
    EventContent = request.json.get("EventContent")
    Event = (NPC_Id,EventStartTime,EventStartDay,EventEndTime,EventPlace,EventContent)
    methodResponse = EventAdd(conn,cursor,Event)
    return APIResponse.make_response(methodResponse)



def EventAdd(conn,cursor,Event):
    try:
        cursor.execute('Insert INTO EventTable (NPC_Id,EventStartTime,EventStartDay,EventEndTime,EventPlace,EventContent) VALUES (?, ?, ?, ?, ?, ?)',Event)
        conn.commit()
        myDict = {'eventId':-1}
        myDict["eventId"] = cursor.lastrowid
        return APIResponse.success(myDict)
    except Error as e:
        return APIResponse.error(str(e))

@app.route("/EventStart",methods=['Post'])
def EventStart():
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    NPC_Id = request.json.get("NPC_Id")
    EventStartTime = request.json.get("EventStartTime")
    EventStartDay = request.json.get("EventStartDay")
    EventPlace = request.json.get("EventPlace")
    EventContent = request.json.get("EventContent")
    Event = (NPC_Id,EventStartTime,EventStartDay,EventPlace,EventContent)
    methodResponse = EventStart(conn,cursor,Event)
    cursor.close()
    conn.close()
    return APIResponse.make_response(methodResponse)



def EventStart(conn,cursor,Event):
    myDict = {'eventId':-1}
    try:
        cursor.execute('Insert INTO EventTable (NPC_Id,EventStartTime,EventStartDay,EventPlace,EventContent) VALUES (?, ?, ?, ?, ?)',Event)
        conn.commit()
        EventId = cursor.lastrowid
        myDict["eventId"] = EventId
        return APIResponse.success(myDict)
    except Error as e:
        return APIResponse.error(str(e))

    
@app.route("/EventEnd",methods=['Post'])
def EventEnd():
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    EventId = request.json.get("EventId")
    EventEndTime = request.json.get("EventEndTime")
    EventContent = request.json.get("EventContent")
    Event = (EventEndTime,EventContent,EventId)
    methodResponse = EventEnd(conn,cursor,Event)
    cursor.close()
    conn.close()
    return APIResponse.make_response(methodResponse)
    
def EventEnd(conn,cursor,Event):
    try:
        cursor.execute("Update EventTable SET EventEndTime = ?, EventContent = EventContent || ? WHERE EventId = ?",Event)
        conn.commit()
        return APIResponse.success(None)
    except Error as e:
        return APIResponse.error(str(e))


# 获得某个NPC的背景故事，包括原始背景、后续记忆以及未概括事件集(接口)
@app.route("/GetBackstory",methods=['Post'])
def GetBackstory():
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    NPC_Id = request.json.get("NPC_Id")
    methodResponse = GetBackstory(conn,cursor,NPC_Id)
    if methodResponse['success']:
        methodResponse['data']['backstory'] = "你是" + methodResponse['data']['backstory']
    cursor.close()
    conn.close()
    return APIResponse.make_response(methodResponse) 

# 获得某个NPC的背景故事，包括原始背景、后续记忆以及未概括事件集(方法)，最后一定会换行
def GetBackstory(conn,cursor,NPC_Id):
    Backstory = ""
    myDict = {'backstory':''}
    try:
        cursor.execute('SELECT NPC_Name, NPC_BaseBackground, NPC_Memory FROM NPCTable WHERE NPC_Id = ?',(NPC_Id,))
        conn.commit()
        name,baseBackground,memory = cursor.fetchone()
        cursor.execute('Select EventStartTime,EventEndTime,EventPlace,EventContent From NPCTable Inner join EventTable on NPCTable.NPC_Id = EventTable.NPC_Id where EventTable.NPC_Id = ? and EventStartDay > NPC_LastMemoryDay order by EventStartDay',(NPC_Id,))
        conn.commit()
        addedEvents = ""
        addedEventsA = cursor.fetchall()
        for event in addedEventsA:
            eventStartTime,eventEndTime,eventPlace,eventContent = event[0],event[1],event[2],event[3]
            if eventEndTime == "" or eventEndTime == None:
                addedEvents = addedEvents + "你于" + eventStartTime + "在" + eventPlace + eventContent + "\n"
            else:
                addedEvents = addedEvents + "你于" + eventStartTime + "在" + eventPlace + eventContent + "直到" + eventEndTime + "\n"
        Backstory = name + "," + baseBackground + '\n' + memory + '\n' + addedEvents
        myDict["backstory"] = Backstory
        return APIResponse.success(myDict)
    except Error as e:
        return APIResponse.error(str(e))
    
def GetAddedBackstory(conn,cursor,NPC_Id):
    addedBackstory = ""
    myDict = {'addedBackstory':''}
    try:
        cursor.execute('SELECT NPC_Memory FROM NPCTable WHERE NPC_Id = ?',(NPC_Id,))
        conn.commit()
        memory = cursor.fetchone()[0]
        cursor.execute('Select EventStartTime,EventEndTime,EventPlace,EventContent From NPCTable Inner join EventTable on NPCTable.NPC_Id = EventTable.NPC_Id where EventTable.NPC_Id = ? and EventStartDay > NPC_LastMemoryDay order by EventStartDay',(NPC_Id,))
        conn.commit()
        addedEvents = ""
        addedEventsA = cursor.fetchall()
        for event in addedEventsA:
            eventStartTime,eventEndTime,eventPlace,eventContent = event[0],event[1],event[2],event[3]
            if eventEndTime == "" or eventEndTime == None:
                addedEvents = addedEvents + "你于" + eventStartTime + "在" + eventPlace + eventContent + "\n"
            else:
                addedEvents = addedEvents + "你于" + eventStartTime + "在" + eventPlace + eventContent + "直到" + eventEndTime + "\n"
        addedBackstory = memory + '\n' + addedEvents
        myDict['addedBackstory'] = addedBackstory
        return APIResponse.success(myDict)
    except Error as e:
        return APIResponse.error(str(e))
    
def GetRelationship(conn,cursor,NPC_Id1,NPC_Id2):
    myDict = {'relationship':''}
    try:
        # 小的ID一定在前，大的ID一定在后
        if NPC_Id1 < NPC_Id2:
            cursor.execute('SELECT RelationalDescription FROM RelationshipTable WHERE NPC_Id1 = ? AND NPC_Id2 = ?',(NPC_Id1,NPC_Id2))
        elif NPC_Id1 > NPC_Id2:
            cursor.execute('SELECT RelationalDescription FROM RelationshipTable WHERE NPC_Id1 = ? AND NPC_Id2 = ?',(NPC_Id2,NPC_Id1))
        conn.commit()
        relationship = cursor.fetchone()[0]
        myDict["relationship"] = relationship
        return APIResponse.success(myDict)
    except Error as e:
        return APIResponse.error(str(e))
    

def GetNPCName(conn,cursor,NPC_Id):
    myDict = {'name':''}
    try:
        cursor.execute("SELECT NPC_Name FROM NPCTable WHERE NPC_Id = ?",(NPC_Id,))
        conn.commit()
        myDict["name"] = cursor.fetchone()[0]
        return APIResponse.success(myDict)
    except Error as e:
        return APIResponse.error(str(e))


if __name__ == '__main__':
    app.run(debug=True,port=8999)